package com.itheima.imclient100;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.SoundPool;

import com.avos.avoscloud.AVOSCloud;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.itheima.imclient100.db.DBUtils;
import com.itheima.imclient100.event.ContactChangedEvent;
import com.itheima.imclient100.event.MessageEvent;
import com.itheima.imclient100.event.OfflineEvent;
import com.itheima.imclient100.utils.ThreadUtils;
import com.itheima.imclient100.utils.ToastUtils;
import com.itheima.imclient100.view.ChatActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.Iterator;
import java.util.List;

/**
 * Created by fullcircle on 2017/7/2.
 */

public class MyApplication extends Application {

    private SoundPool soundPool;
    private int duan;
    private int yulu;

    @Override
    public void onCreate() {
        super.onCreate();
        initEMClient();

        // 初始化LeanCloud参数依次为 this, AppId, AppKey
        AVOSCloud.initialize(this,"rU7CFMKuCikTNvjBb4EqmIPM-gzGzoHsz","Uyf0s4rmkowaRB7Wj7NbNte6");
        //开启LeanCloud的debug模式
        AVOSCloud.setDebugLogEnabled(true);

        //初始化数据库工具类
        DBUtils.initDBUtils(this);

        //初始加载音频文件
        initSoundPool();
    }

    private void initSoundPool() {
        //参数1 当前soundpool(声音池)加载的最大音频数量
        //参数2  加载声音的类型  STREAM_MUSIC 媒体文件
        //参数3 目前没有用 设计的目的是设置当前音频的质量 传入0作为默认值
        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
        //load 加载音频 参数1 上下文 参数2 要加载的音频资源id 参数3 没用 建议传入1
        duan = soundPool.load(this, R.raw.duan, 1);
        yulu = soundPool.load(this, R.raw.yulu, 1);
    }

    private void initEMClient() {
        EMOptions options = new EMOptions();
// 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);

        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
// 如果APP启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        //如果当前进程名字和包名不同 说明这个进程不是应用的主进程
        if (processAppName == null ||!processAppName.equalsIgnoreCase(this.getPackageName())) {
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
//初始化
        EMClient.getInstance().init(this, options);
//在做打包混淆时，关闭debug模式，避免消耗不必要的资源  开启debug模式会输出大量日志 上线时要关掉
        EMClient.getInstance().setDebugMode(true);
        //设置联系人相关的监听器
        EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {

            @Override
            public void onContactInvited(final String username, final String reason) {
                //收到好友邀请
                ThreadUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast(getApplicationContext(),username+reason);
                    }
                });

                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //接受好友的请求 同意添加好友
                            EMClient.getInstance().contactManager().acceptInvitation(username);
                            //declineInvitation拒绝好友请求
                           // EMClient.getInstance().contactManager().declineInvitation();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }

            @Override
            public void onFriendRequestAccepted(String s) {
                //别人接受了当前用户加好友的请求
            }

            @Override
            public void onFriendRequestDeclined(String s) {
                //别人拒绝了当前用户加好友的请求
            }

            @Override
            public void onContactDeleted(String username) {
                //被删除时回调此方法
                System.out.println(username+"被删除");
                //ToastUtils.showToast(getApplicationContext(),username+"被删除");
                EventBus.getDefault().post(new ContactChangedEvent(false,username));
            }


            @Override
            public void onContactAdded(String username) {
                //增加了联系人时回调此方法
                EventBus.getDefault().post(new ContactChangedEvent(true,username));
            }
        });

        EMMessageListener msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                EventBus.getDefault().post(new MessageEvent());
                //根据当前的应用处于前台还是后台 决定播放哪个声音
                if(isForegroundApp()){
                    //参数1 要播放的音频资源对应的序号 就是Load方法的返回值
                    //参数2 参数3 左右声道音量 0~1
                    //参数4 播放的质量 0代表最低质量
                    //参数5 是否循环 0 不循环 -1 无限循环
                    //参数6 播放的速度 0.5~2.0 如果传入1 正常速度播放
                    soundPool.play(duan,1,1,1,0,1);
                }else{
                    soundPool.play(yulu,1,1,1,0,1);
                    //如果处于后台状态 那么发送一个通知
                    sendNotification(messages.get(0));
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        };

        EMClient.getInstance().chatManager().addMessageListener(msgListener);

//注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());

    }



    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    public boolean isForegroundApp(){
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(500);
        if(runningTasks.get(0).topActivity.getPackageName().equals(getPackageName())){
            //获取正在运行的所有任务 如果第一个任务的包名和当前应用的包名一致 说明应用处于前台否则处于后台
            return true;
        }else{
            return false;
        }

    }


    private void sendNotification(EMMessage msg){
        Notification.Builder builder = new Notification.Builder(this);
        //setTicker 5.0以后的版本 ticker 在状态栏里滚动的文字没有效果了
        builder.setTicker("有新的消息");
        builder.setContentTitle(msg.getFrom()+"发来消息");
        EMTextMessageBody body = (EMTextMessageBody) msg.getBody();
        builder.setContentText(body.getMessage());
        //设置小图标
        builder.setSmallIcon(R.mipmap.message);
        //设置大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.avatar8));

        Intent intent = new Intent(this,MainActivity.class);
        Intent intent2 = new Intent(this, ChatActivity.class);
        intent2.putExtra("username",msg.getFrom());
        Intent[] intents= new Intent[]{intent,intent2};
        //延迟意图 只有当通知点击的时候 才会触发意图 可以操作 activity activity的数组 service 发广播
        PendingIntent pendingIntent  = PendingIntent.getActivities(this,1,intents,PendingIntent.FLAG_UPDATE_CURRENT);
        //设置了contentIntent之后 点击通知 触发PendingIntent 如果设置为setAutoCancel 通知就会自动消失
        builder.setContentIntent(pendingIntent);
        //点击之后通知消失
        builder.setAutoCancel(true);

        Notification notification = builder.getNotification();
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(1,notification);
    }


    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }
        @Override
        public void onDisconnected(final int error) {
            ThreadUtils.runOnMainThread(new Runnable() {

                @Override
                public void run() {
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        EventBus.getDefault().post(new OfflineEvent());
                    } else {

                    }
                }
            });
        }
    }
}
